import { Button, Table, Space, Modal } from 'antd';
import type { TableProps } from 'antd';
import '../dealership/css/region.css';
import carMock from '@/mock/carMock';
import { useEffect, useState } from "react";

export default function Region() {
  interface DataType {
    _id: string;
    code: String;
    carrand: String;
    carmodel: Number;
    carbody: String;
    holder: String;
  }

  // 从 localStorage 加载数据
  const loadCarData = () => {
    const storedData = localStorage.getItem('carData');
    if (storedData) {
      return JSON.parse(storedData);
    }
    return carMock; 
  };

  const [car, setCar] = useState<DataType[]>(loadCarData); 
  const [pagesize, setPagesize] = useState(5); 
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); 

  useEffect(() => {
    localStorage.setItem('carData', JSON.stringify(car));
  }, [car]); 

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '车牌号',
      dataIndex: 'code',
      key: 'code',
      width: '200px',
      render: (text) => <span>{text}</span>,
      align: 'center',
    },
    {
      title: '车辆品牌',
      dataIndex: 'carrand',  // 修正为正确的字段名
      key: 'carrand',
      render: (text) => <span>{text}</span>,
      width: '300px',
      align: 'center',
    },
    {
      title: '车辆型号',
      dataIndex: 'carmodel',
      key: 'carmodel',
      render: (text) => <span>{text}</span>,
      width: '300px',
      align: 'center',
    },
    {
      title: '车身',
      dataIndex: 'carbody',
      key: 'carbody',
      render: (text) => <span>{text}</span>,
      width: '250px',
      align: 'center',
    },
    {
      title: '持有人',
      dataIndex: 'holder',
      key: 'holder',
      render: (text) => <span>{text ? text : '无'}</span>,  // 如果没有 holder 字段，则显示 '无'
      width: '250px',
      align: 'center',
    },
    
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleDelete(record._id)}>编辑</a>
          <a onClick={() => handleDelete(record._id)}>删除</a>
        </Space>
      ),
      width: '250px',
      align: 'center',
    },
  ];

  // 选中数据的回调函数
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 删除单个数据的回调函数
  const handleDelete = (id: string) => {
    // 弹出确认框
    Modal.confirm({
      title: '确定要删除这条数据吗?',
      content: '删除后数据无法恢复，请谨慎操作。',
      onOk: () => {
        const newCarList = car.filter(item => item._id !== id);
        setCar(newCarList); // 更新状态
      },
      onCancel() {
        console.log('取消删除');
      },
    });
  };

  // 批量删除的回调函数
  const handleBatchDelete = () => {
    // 如果没有选中行，直接提醒
    if (selectedRowKeys.length === 0) {
      Modal.info({
        title: '提示',
        content: '请先选择要删除的数据。',
      });
      return;
    }

    // 弹出确认框
    Modal.confirm({
      title: '确定要删除选中的数据吗?',
      content: `删除后数据无法恢复，请谨慎操作。您将删除 ${selectedRowKeys.length} 条数据。`,
      onOk: () => {
        // 根据选中的行的 ID 删除数据
        const newCarList = car.filter(item => !selectedRowKeys.includes(item._id));
        setCar(newCarList); // 更新状态

        // 清空选中的行
        setSelectedRowKeys([]);

        // 更新 localStorage
        localStorage.setItem('carData', JSON.stringify(newCarList));
      },
      onCancel() {
        console.log('取消删除');
      },
    });
  };

  return (
    <div className='region'>
      <div className='region-title'>
        <p className='region-text'>车辆列表</p>
        <div className='region-btn'>
          <Button type="primary" style={{ marginTop: '10px' }}>
            +新建
          </Button>
          <Button
            type="default"
            style={{ marginTop: '10px', marginLeft: '30px' }}
            onClick={handleBatchDelete}
          >
            批量删除
          </Button>
        </div>
      </div>
      <div className='region-table' style={{ marginTop: '20px', marginLeft: "20px" }}>
        <Table<DataType>
          rowSelection={{
            type: 'checkbox',
            onChange: onSelectChange,
            selectedRowKeys, // 管理选中的行
          }}
          columns={columns}
          dataSource={car}
          rowKey="_id"
          pagination={{
            position: ["bottomCenter"],
            pageSize: pagesize,
            total: car.length,
            showSizeChanger: true,
            pageSizeOptions: [3, 5, 7, 9],
            onShowSizeChange: (current, pageSize) => {
              setPagesize(pageSize);
            }
          }}
        />
      </div>
    </div>
  );
}
